using Digitalmes.Common.Jwt;

namespace Digitalmes.ApiService.Middleware;

/// <summary>
/// JWT 中间件，用于刷新 Token
/// </summary>
public sealed class JwtMiddleware
{
    private readonly string[] _ignoreUrls =
    {
        "swagger",
        "/fytapiui",
        "/chathub",
        "/channelhub",
        "/api-config",
        "/fyt",
        "/upload/",
    };

    private readonly RequestDelegate _next;

    public JwtMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        if (context.Request.Method == "OPTIONS")
        {
            return _next(context);
        }

        //过滤，不要验证token的url
        if (_ignoreUrls.Any(s => context.Request.Path.Value.Contains(s, StringComparison.OrdinalIgnoreCase)))
        {
            return _next(context);
        }

        // 自动刷新token
        if (!context.Request.Headers.TryGetValue(JwtConstant.TokenName, out var token) || string.IsNullOrEmpty(token))
        {
            return _next(context);
        }

        var jwtToken = JwtAuthHandler.SerializeJwt(token!);
        var ts = DateTime.Now.Subtract(jwtToken.Time);
        if (ts.Minutes is <= 30 or >= 60) 
            return _next(context);

        var newToken = JwtAuthHandler.IssueJwt(new()
        {
            Id = jwtToken.Id,
            FullName = jwtToken.FullName,
            Role = jwtToken.Role,
            RoleArray = jwtToken.RoleArray,
            TenantId = jwtToken.TenantId,
            Time = DateTime.Now,
        });
        context.Response.Headers.Append("X-Refresh-Token", newToken);
        return _next(context);
    }
}
